package com.ycsj.goldmedalnewconcept.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mob.MobSDK;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.bean.timeresq;
import com.ycsj.goldmedalnewconcept.constant.ConfigConstant;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.constant.NetConstant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;

/**
 * 使用WebView播放视频时需要注意的地方： 1、加网络访问权限（及其他所需要的权限）；
 * 2、WebViewClient中方法shouldOverrideUrlLoading可用来实现点击webView页面的链接；
 * 3、WebView中播放视频需要添加webView.setWebChromeClient(new WebChromeClient())；
 * 4、视频竖屏时，点击全屏，想要切换到横屏全屏的状态，那么必须在Manifest.xml配置文件该Activity的
 * 配置文件中添加android:configChanges="orientation|screenSize"语句。
 * 5、如果视频不能播放，或者播放比较卡，可以采用硬件加速，即在Application，或所在的Activity的配置文件中添加
 * android:hardwareAccelerated="true"即可。
 * 
 * @author zhongyao
 */

@SuppressLint("SetJavaScriptEnabled")
public class GrammarThirdActivity extends BaseJpStarActivity {
	private WebView webView;
	private WebView webView2;
	private FrameLayout video_fullView;// 全屏时视频加载view
	private View xCustomView;
	private ProgressDialog waitdialog = null;
	private CustomViewCallback xCustomViewCallback;
	private ProgressBar mprogressBar;
	private String oldtotal;
	private MediaPlayer mPlayer;

	// private TextView tv_html_title;
	// private TextView tv_word_back;
	// private ImageView iv_share;

	@SuppressLint("JavascriptInterface")
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_PROGRESS);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		setContentView(R.layout.activity_grammar);
		final Handler handler = new Handler();
//		initRegisterBroadCast();

		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		width = metric.widthPixels;
		height2 = metric.heightPixels;

		boolean isfirst = getIntent().getBooleanExtra("isfirst", true);
		// iv_share = (ImageView) findViewById(R.id.iv_share);
		ll_webview = (LinearLayout) findViewById(R.id.ll_webview);
		// tv_html_title = (TextView) findViewById(R.id.tv_html_title);
		// tv_word_back = (TextView) findViewById(R.id.tv_word_back);
		// tv_word_back.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// finish();
		// }
		// });

		// iv_share.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// if ("".equals(Score) && "".equals(Time)) {
		// // deleteShare();
		// clickShare(v);
		// } else {
		// clickShare2();
		// }
		// }
		// });

		webView = (WebView) findViewById(R.id.webView);
		webView2 = (WebView) findViewById(R.id.webView2);
		lESSON_ID = getIntent().getStringExtra("lESSON_ID");
		String LESSON_NAME = getIntent().getStringExtra("LESSON_NAME");
		// tv_html_title.setText(LESSON_NAME);
		// getWindow().addFlags(
		// WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

		// 让webview去加载网页
		// webView.loadUrl("http://10.0.2.2:8080/");
		// webView.loadUrl(NetConstant.H5
		// + "App_Class/H5/ReqParaFromApp.aspx?account="
		// + SPUtils.getString(this, ConfigConstant.USERNAME)
		// + "&type=4&lessonid=" + lESSON_ID);
		Log.e("home",
				NetConstant.H5 + "App_Class/H5/ReqParaFromApp.aspx?account="
						+ SPUtils.getString(this, ConfigConstant.USERNAME)
						+ "&type=4&lessonid=" + lESSON_ID);
		// 没有显示出点击展开全文的原因是：webview默认没有开启javascript功能
		// 因为webview上有很多设置，所以webview把设置都封装到WebSettings类中了
		WebSettings settings = webView.getSettings();
		WebSettings settings2 = webView2.getSettings();

		settings.setJavaScriptEnabled(true);
		webView2.getSettings().setJavaScriptEnabled(true);
		webView2.getSettings().setBuiltInZoomControls(false);
		webView2.getSettings().setUseWideViewPort(true);
		webView2.getSettings().setRenderPriority(RenderPriority.HIGH);
		webView2.getSettings().setDatabaseEnabled(true);
		webView2.getSettings().setDomStorageEnabled(true);
		webView2.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
		webView2.getSettings().setPluginState(PluginState.ON);

		// webView2.getSettings().setRenderPriority(RenderPriority.HIGH);
		// mWebView.getSettings().setBlockNetworkImage(true);
		webView2.loadData("", "text/html", null);
		// webView2.getSettings().setPluginState(PluginState.ON);
		// mWebView.setInitialScale(39);
		webView2.setWebViewClient(client);
		webView2.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				// TODO Auto-generated method stub
				// MainActivity.this.setProgress(newProgress * 100);
				// mprogressBar.setProgress(newProgress);

			}
		});
		int VERSION_SDK_ELEVEN = 14;
		// webview可以设置监听得到各种事件
		// 1 WebViewClient 比较简单的监听
		// webView.setWebViewClient(client);
		// 2 比较复杂、高级的监听
		// 硬件加速 privatevoidhardwareAccelerate(){
		// if (VERSION.SDK_INT > VERSION_SDK_ELEVEN)
		// {
		// getWindow().setFlags(
		// WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
		// WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
		// }

		// webView2.getSettings().setPluginState(PluginState.ON);
		// webView2.getSettings().setAllowFileAccess(true);

		// webView.setWebChromeClient(chromeClient);
		// webView2.setWebChromeClient(chromeClient);
		// 设置文字大小
		// 从sp中读取String -->TextSize
		webView.setVisibility(View.GONE);

		webView2.addJavascriptInterface(new WebAppInterface(this), "Android");
		// webView2.loadUrl(NetConstant.H5
		// + "html5/AndroidPage/Android_pageInfo.html");
//		webView2.loadUrl(Constant.SERVER_tk + ":36356/jpjNewPage/question.html");
		webView2.loadUrl("https://moregolden.com:25697/question.html");
	}

	/**
	 * 注册广播
	 */
	private void initRegisterBroadCast() {

		IntentFilter filter = new IntentFilter();
		filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(new TimingReceiver(), filter);
	}

	/**
	 * 断网计时广播接受者
	 * 
	 * @author Administrator
	 *
	 */
	class TimingReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

			// 监听网络连接，包括wifi和移动数据的打开和关闭,以及连接上可用的连接都会接到监听
			if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent
					.getAction())) {
				// 获取联网状态的NetworkInfo对象
				NetworkInfo info = intent
						.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
				if (info != null) {
					// 如果当前的网络连接成功并且网络连接可用
					if (NetworkInfo.State.CONNECTED == info.getState()
							&& info.isAvailable()) {
						if (info.getType() == ConnectivityManager.TYPE_WIFI
								|| info.getType() == ConnectivityManager.TYPE_MOBILE) {

							Log.i("test", "网络重新连接");

							String gradeid = String.valueOf(lESSON_ID)
									.substring(0, 4);
							HttpUtils httpUtils2 = new HttpUtils();
							httpUtils2.configCurrentHttpCacheExpiry(1000);
							httpUtils2
									.send(HttpMethod.GET,
											NetConstant.USERONLINE
													+ "InitInterfaceBegin.aspx?msg=1&type=3&account="
													+ SPUtils
															.getString(
																	GrammarThirdActivity.this,
																	"account")
													+ "&gradeid=" + gradeid
													+ "&lessonid=" + lESSON_ID,
											callBackTime);
						}
					}
				}
			}
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (mediaPlayer != null) {

			mediaPlayer.pause();
		}

		HttpUtils httpUtils2 = new HttpUtils();
		httpUtils2.configCurrentHttpCacheExpiry(1000);
		httpUtils2.send(HttpMethod.GET, NetConstant.USERONLINE
				+ "SaveInterfaceEnd.aspx?msg=1&rid=" + rid + "&account="
				+ SPUtils.getString(this, ConfigConstant.USERNAME),
				callBackTimefinish);

	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.release();
			mediaPlayer = null;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		webView2.setVisibility(View.GONE);
		webView.removeAllViews();
		webView.destroy();
		webView2.removeAllViews();
		webView2.destroy();
		if (webView != null) {
			webView = null;
		}
		if (webView2 != null) {
			webView2 = null;
		}
		System.gc();
	}

	@Override
	public void finish() {
		ViewGroup view = (ViewGroup) getWindow().getDecorView();
		view.removeAllViews();
		super.finish();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		String gradeid = String.valueOf(lESSON_ID).substring(0, 4);
		HttpUtils httpUtils2 = new HttpUtils();
		httpUtils2.configCurrentHttpCacheExpiry(1000);
		httpUtils2.send(HttpMethod.GET,
				NetConstant.USERONLINE
						+ "InitInterfaceBegin.aspx?msg=1&type=4&account="
						+ SPUtils.getString(this, ConfigConstant.USERNAME)
						+ "&gradeid=" + gradeid + "&lessonid=" + lESSON_ID,
				callBackTime);
	}

	private WebChromeClient chromeClient = new WebChromeClient() {

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			if (newProgress == 100) {
				
			}
		}

	};

	private WebViewClient client = new WebViewClient() {
		// 当页面加载完成之后会调用此方法
		@Override
		public void onPageFinished(WebView view, String url) {

		}

	};

	public int getPhoneSDKInt() {
		int version = 0;
		try {
			version = Integer.valueOf(android.os.Build.VERSION.SDK);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return version;
	}

	private String rid;

	private String lESSON_ID;

	private MediaPlayer mediaPlayer;
	private LinearLayout ll_webview;
	private int width;
	private int height2;
	private PopupWindow popup;
	private Button bt;
	private String Score = "";
	private String Time = "";

	public class WebAppInterface {
		Context mContext;
		private EditText et;

		/** Instantiate the interface and set the context */
		WebAppInterface(Context c) {
			mContext = c;
		}

		/** Show a toast from the web page */
		@JavascriptInterface
		public void showToast(String toast) {
			if (mediaPlayer != null) {
				mediaPlayer.stop();
			}
			mediaPlayer = new MediaPlayer();
			String uri;
			// Toast.makeText(mContext, toast, 0).show();
			if ("http".equals(toast.substring(0, 4))) {
				uri = toast;
			} else {

				uri = NetConstant.H5 + "html5/" + toast;
			}

			mediaPlayer.reset();
			try {
				mediaPlayer.setDataSource(uri);
				mediaPlayer.prepare();
				mediaPlayer.start();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// prepare之后自动播放
			//

		}

		@SuppressLint({"NewApi", "ResourceAsColor"})
		@JavascriptInterface
		public void usePopup2(final String wrongtext, final String anwser) {

			LayoutInflater mInflater = LayoutInflater
					.from(GrammarThirdActivity.this);
			ViewGroup rootView = (ViewGroup) mInflater.inflate(
					R.layout.popwindow, null);
			rootView.setLayoutParams(new LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			et = (EditText) rootView.findViewById(R.id.et);
			LinearLayout ll_main = (LinearLayout) rootView
					.findViewById(R.id.ll_main);
			Animation slide_up_in = AnimationUtils.loadAnimation(
					GrammarThirdActivity.this, R.anim.slide_up_in);
			ll_main.startAnimation(slide_up_in);
			TextView tv_wrongtext = (TextView) rootView
					.findViewById(R.id.tv_wrongtext);
			final String wrongtextreplace = wrongtext.replaceAll("\\\\", "");
			final String anwserreplace = anwser.replaceAll("\\\\'", "'");
			tv_wrongtext.setText(wrongtextreplace);

			final ImageView iv_xx = (ImageView) rootView
					.findViewById(R.id.iv_xx);
			final Animation rotate = AnimationUtils.loadAnimation(
					GrammarThirdActivity.this, R.anim.rotate);

			final ImageView iv = (ImageView) rootView.findViewById(R.id.iv);
			final Animation left_in = AnimationUtils.loadAnimation(
					GrammarThirdActivity.this, R.anim.left_in);
			iv.startAnimation(left_in);
			left_in.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation animation) {

				}

				@Override
				public void onAnimationRepeat(Animation animation) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onAnimationEnd(Animation animation) {
					iv.startAnimation(left_in);

				}
			});

			// popup = new PopupWindow(GrammarThirdActivity.this);
			popup = new PopupWindow(rootView, width,
					WindowManager.LayoutParams.WRAP_CONTENT, true);
			popup.setContentView(rootView);

			// setContentView之前一定要设置宽高，否则不显示
			popup.setWidth(width * 3 / 4);
			// popup.setHeight(height2*6/15);
			// popup.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
			popup.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
			// 去掉默认的背景
			popup.setBackgroundDrawable(new ColorDrawable(
					android.R.color.transparent));

			// 点击空白处的时候PopupWindow会消失
			// popup.setTouchable(true);
			// 如果focusable为false，在一个Activity弹出一个PopupWindow，按返回键，由于PopupWindow没有焦点，会直接退出Activity。如果focusable为true，PopupWindow弹出后，所有的触屏和物理按键都有PopupWindows处理。
			popup.setOutsideTouchable(false);
			popup.setFocusable(true);

			popup.showAtLocation((View) ll_webview.getParent(),
					Gravity.NO_GRAVITY, width / 9, height2 * 3 / 10);

			bt = (Button) rootView.findViewById(R.id.bt);
			bt.setClickable(true);
			bt.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					final String string = et.getText().toString().trim();

					bt.setClickable(false);
					if ("".equals(string)) {
						Toast.makeText(GrammarThirdActivity.this, "不能为空", Toast.LENGTH_SHORT)
								.show();
					} else {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								// webView2.loadUrl("javascript:demo09check("+string+","+anwser+")");
								// Toast.makeText(MainActivity.this, anwser,
								// 0).show();

								final String stringreplace = string.replaceAll(
										"'", "\\\\'");
								webView2.loadUrl("javascript:demo09check('"
										+ wrongtext + "->" + stringreplace
										+ "','" + anwser + "')");

							}
						});
					}

					Handler handler = new Handler();
					handler.postDelayed(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							popup.dismiss();
						}
					}, 100);
				}
			});
			
			iv_xx.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					iv_xx.startAnimation(rotate);
					Handler handler = new Handler();
					handler.postDelayed(new Runnable() {

						@Override
						public void run() {
							popup.dismiss();
						}
					}, 100);

				}
			});
		}

		@JavascriptInterface
		public void getScore(String score, String time) {
			Log.e("yubo", score + "分-=-=" + Time + "秒");
			Score = score;
			Time = time.replaceAll("秒", "");
		}

		// 传递参数
		@JavascriptInterface
		public String getParam() {

			String param = SPUtil.getString(mContext, ConfigConstant.USERNAME,
					"")
					+ ",4,"
					+ lESSON_ID
					+ ","
					+ SPUtil.getString(mContext, "role", "");
			Log.e("test", "param=" + param);
			return param;
		}

		// 关闭界面
		@JavascriptInterface
		public void finish() {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					GrammarThirdActivity.this.finish();
				}
			});
			Log.e("test", "finish");
			return;
		}

		// 重新做题
		@JavascriptInterface
		public void againtest() {

			Log.e("test", "againtest");

			new Thread(new Runnable() {
				@Override
				public void run() {

					Intent intent = new Intent(mContext,
							GrammarThirdActivity.class);
					intent.putExtra("lESSON_ID", lESSON_ID);
					mContext.startActivity(intent);

				}
			}).start();
			GrammarThirdActivity.this.finish();
			return;
		}

		// 分享界面
		@JavascriptInterface
		public void share(final String total) {
			oldtotal = total;

			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					String[] StrArray = total.split("&");
					clickShare(StrArray[3], StrArray[4]);
					Log.e("test", "total=" + total);

				}
			});

			return;
		}


		// 播放正误音频
		@JavascriptInterface
		public void playertrueorfalse(int num) {
			Log.i("test",num+"num");

			if (mPlayer != null) {
				mPlayer.release();
				mPlayer = null;
			}
			if(num==1){

				mPlayer = MediaPlayer.create(GrammarThirdActivity.this, R.raw.rightmp3);
			}else if(num==2){

				mPlayer = MediaPlayer.create(GrammarThirdActivity.this, R.raw.errormp3);
			}
			mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {
					if (mPlayer != null) {
						mPlayer.release();
						mPlayer = null;
					}
				}
			});
			mPlayer.start();
			return;
		}
	}

	public void clickShare(final String totaltime, final String Score) {

		// TODO Auto-generated method stub
		MobSDK.init(GrammarThirdActivity.this, "12c24ea0b59b0",
				"aae63565fbd69b1acbfcdd0d5ac0b35c");
		OnekeyShare oks = new OnekeyShare();
		// 关闭sso授权
		oks.disableSSOWhenAuthorize();
		oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {

			@Override
			public void onShare(Platform platform, ShareParams paramsToShare) {
				if (SinaWeibo.NAME.equals(platform.getName())) {
					paramsToShare.setTitle(getString(R.string.share));
					// titleUrl是标题的网络链接，仅在人人网和QQ空间使用

					String url = Constant.SERVER_tk+"/tkNewPage/sharePage/share-report.html?"+oldtotal;
					
					String title = SPUtils.getString(GrammarThirdActivity.this,
							"name")
							+ "在"
							+ "语法突破"
							+ "环节花费了"
							+ totaltime.substring(5, totaltime.length())
							+ "秒获得"
							+ Score.substring(5, Score.length())
							+ "分,为你点赞！";
					int unicodeJoy = 0x1F44D;
					String emojiString = new String(Character
							.toChars(unicodeJoy));
					paramsToShare.setTitleUrl(Constant.SERVER_tk+"/tkNewPage/sharePage/share-report.html?"+oldtotal);
					paramsToShare.setTitle(SPUtils.getString(
							GrammarThirdActivity.this, "name")
							+ "在"
							+ "语法突破"
							+ "环节花费了"
							+ totaltime.substring(5, totaltime.length())
							+ "秒获得"
							+ Score.substring(5, Score.length())
							+ "分,为你点赞！");
					// text是分享文本，所有平台都需要这个字段
					paramsToShare.setText(title + "\n\r想展现你的实力吗?来这里比拼一下吧！"
							+ url);
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
					paramsToShare
							.setImageUrl("http://139.129.57.83:8080/Appandroid/applogo.png");
					// url仅在微信（包括好友和朋友圈）中使用
					paramsToShare.setUrl(Constant.SERVER_tk+"/tkNewPage/sharePage/share-report.html?"+oldtotal);
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					paramsToShare.setComment("");
					// site是分享此内容的网站名称，仅在QQ空间使用
					paramsToShare.setSite(getString(R.string.app_name));
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					paramsToShare.setSiteUrl(Constant.SERVER_tk+"/tkNewPage/sharePage/share-report.html?"+oldtotal);

				} else {
					paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
					paramsToShare.setTitle(getString(R.string.share));
					// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
					paramsToShare.setTitleUrl(Constant.SERVER_tk+"/tkNewPage/sharePage/share-report.html?"+oldtotal);
					paramsToShare.setTitle(SPUtils.getString(
							GrammarThirdActivity.this, "name")
							+ "在"
							+ "语法突破"
							+ "环节花费了"
							+ totaltime.substring(5, totaltime.length())
							+ "秒获得"
							+ Score.substring(5, Score.length())
							+ "分,为你点赞！");
					// text是分享文本，所有平台都需要这个字段
					paramsToShare.setText("想展现你的实力吗?来这里比拼一下吧！");
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
					paramsToShare
							.setImageUrl("http://139.129.57.83:8080/Appandroid/applogo.png");
					// url仅在微信（包括好友和朋友圈）中使用
					paramsToShare.setUrl(Constant.SERVER_tk+"/tkNewPage/sharePage/share-report.html?"+oldtotal);
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					paramsToShare.setComment("");
					// site是分享此内容的网站名称，仅在QQ空间使用
					paramsToShare.setSite(getString(R.string.app_name));
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					paramsToShare.setSiteUrl("http://m.moregolden.com:36356/scorePage.html?"+oldtotal);

				}
			}
		});
		// 分享时Notification的图标和文字 2.5.9以后的版本不 调用此方法
		// oks.setNotification(R.drawable.ic_launcher,
		// getString(R.string.app_name));
		// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用

		// 启动分享GUI
		oks.show(this);
	}


	private RequestCallBack<String> callBackTimefinish = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			// TODO Auto-generated method stub
			String json = responseInfo.result;
			// 使用Gson把json解析成对象
			// 1 得到gson对象

			// Log.i("testtime", json.toString());
		}

		@Override
		public void onFailure(HttpException error, String msg) {
			// TODO Auto-generated method stub

		}
	};

	private RequestCallBack<String> callBackTime = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			// TODO Auto-generated method stub
			String json = responseInfo.result;
			// 使用Gson把json解析成对象
			// 1 得到gson对象

			Log.i("json", json);

			Gson gson = new Gson();
			timeresq fromJson = gson.fromJson(json, timeresq.class);
			rid = fromJson.rid;
			Log.e("RID", "rid" + rid);
		}

		@Override
		public void onFailure(HttpException error, String msg) {
			// TODO Auto-generated method stub
			rid = "";
		}
	};

	public void clickShare(View v) {
		// 得到当前view所在view结构中的根view
		View vv = v.getRootView();
		// 设置属性
		vv.setDrawingCacheEnabled(true);

		// 取得位图
		Bitmap bm = vv.getDrawingCache();

		Resources res = getResources();
		Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.ycsjlogo);
		Bitmap watermarkBitmap = watermarkBitmap(
				bm,
				bmp,
				"金牌君使用者："
						+ SPUtils.getString(GrammarThirdActivity.this, "name"));
		// iv.setImageBitmap(watermarkBitmap);
		try {
			saveFile(watermarkBitmap, "out.jpg");
			sharePic();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		vv.destroyDrawingCache();
	}

	/**
	 * 保存文件
	 * 
	 * @param bm
	 * @param fileName
	 * @throws IOException
	 */
	public void saveFile(Bitmap bm, String fileName) throws IOException {
		String path = getSDPath() + "/goldupload/";
		File dirFile = new File(path);
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}

		File myCaptureFile = new File(path + fileName);
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(myCaptureFile));
		bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
		bos.flush();
		bos.close();
	}

	public String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
		} else {
			sdDir = getFilesDir();
		}
		return sdDir.toString();
	}

	/**
	 * 加水印 也可以加文字
	 * 
	 * @param src
	 * @param watermark
	 * @param title
	 * @return
	 */
	public static Bitmap watermarkBitmap(Bitmap src, Bitmap watermark,
			String title) {
		if (src == null) {
			return null;
		}
		int w = src.getWidth();
		int h = src.getHeight();
		// 需要处理图片太大造成的内存超过的问题,这里我的图片很小所以不写相应代码了

		Bitmap newb = Bitmap.createBitmap(w, h, Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
		Canvas cv = new Canvas(newb);
		cv.drawBitmap(src, 0, 0, null);// 在 0，0坐标开始画入src
		Paint paint = new Paint();
		// 加入图片
		if (watermark != null) {
			int ww = watermark.getWidth();
			int wh = watermark.getHeight();
			// paint.setAlpha(50);
			cv.drawBitmap(watermark, w - ww - 5, h * 3 / 4, paint);// 在src的右下角画入水印
			// cv.drawBitmap(watermark, 0, 0, paint);// 在src的左上角画入水印
		} else {
			Log.i("i", "water mark failed");
		}
		// 加入文字
		if (title != null) {
			String familyName = "宋体";
			Typeface font = Typeface.create(familyName, Typeface.NORMAL);
			TextPaint textPaint = new TextPaint();
			textPaint.setColor(Color.RED);
			// textPaint.setAlpha(52);
			textPaint.setTypeface(font);
			textPaint.setTextSize(20);
			// 这里是自动换行的
			// StaticLayout layout = new
			// StaticLayout(title,textPaint,w,Alignment.ALIGN_OPPOSITE,1.0F,0.0F,true);
			// layout.draw(cv);
			// 文字就加左上角算了
			cv.drawText(title, w / 5, h * 7 / 8, textPaint);
		}
		cv.save(Canvas.ALL_SAVE_FLAG);// 保存
		cv.restore();// 存储
		return newb;
	}

	public void sharePic() {
		// ShareSDK.initSDK(WordsFuxiActivity.this);
		MobSDK.init(GrammarThirdActivity.this, "12c24ea0b59b0",
				"aae63565fbd69b1acbfcdd0d5ac0b35c");
		OnekeyShare oks = new OnekeyShare();
		// 关闭sso授权
		oks.disableSSOWhenAuthorize();
		oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {

			@Override
			public void onShare(Platform platform, ShareParams paramsToShare) {
				// if(QZone.NAME.equals(platform.getName())){
				// paramsToShare.setTitleUrl("http://139.129.57.83:8080/Appandroid/APPicon192.png");
				// paramsToShare.setImagePath(getSDPath()+"/goldupload/out.jpg");
				// paramsToShare.setImageUrl("http://139.129.57.83:8080/Appandroid/APPicon192.png");
				// // comment是我对这条分享的评论，仅在人人网和QQ空间使用
				// paramsToShare.setComment("");
				// // site是分享此内容的网站名称，仅在QQ空间使用
				// paramsToShare.setSite(getString(R.string.app_name));
				// // siteUrl是分享此内容的网站地址，仅在QQ空间使用
				// paramsToShare.setSiteUrl("http://139.129.57.83:8080/Appandroid/APPicon192.png");
				// }
				if (SinaWeibo.NAME.equals(platform.getName())) {
					paramsToShare.setText("");
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
					// paramsToShare.setImageUrl("http://139.129.57.83:8080/Appandroid/APPicon192.png");
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					paramsToShare.setImagePath(getSDPath()
							+ "/goldupload/out.jpg");// 确保SDcard下面存在此张图片
				} else if (QQ.NAME.equals(platform.getName())) {
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					paramsToShare.setImagePath(getSDPath()
							+ "/goldupload/out.jpg");// 确保SDcard下面存在此张图片
					// oks.seti
					// url仅在微信（包括好友和朋友圈）中使用
					// oks.setUrl(list.get(0).WEB_URL);
					// 微信分享必须设置否则发送文本信息
					// oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
					paramsToShare
							.setImageUrl("http://139.129.57.83:8080/Appandroid/APPicon192.png");
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					paramsToShare.setComment("");
					// site是分享此内容的网站名称，仅在QQ空间使用
					paramsToShare.setSite(getString(R.string.app_name));
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					paramsToShare
							.setSiteUrl("http://139.129.57.83:8080/Appandroid/APPicon192.png");

				} else {
					paramsToShare.setShareType(Platform.SHARE_IMAGE);
					paramsToShare.setTitle("wer");
					// paramsToShare.setText("ces");
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					paramsToShare.setImagePath(getSDPath()
							+ "/goldupload/out.jpg");// 确保SDcard下面存在此张图片
					// paramsToShare.setUrl("http://www.baidu.com");
					// paramsToShare.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
					// oks.seti
					// url仅在微信（包括好友和朋友圈）中使用
					// oks.setUrl(list.get(0).WEB_URL);
					// 微信分享必须设置否则发送文本信息
					// oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					// paramsToShare.setComment("");
					// // site是分享此内容的网站名称，仅在QQ空间使用
					// paramsToShare.setSite(getString(R.string.app_name));
					// // siteUrl是分享此内容的网站地址，仅在QQ空间使用
					// paramsToShare.setSiteUrl("http://139.129.57.83:8080/Appandroid/APPicon192.png");

				}

			}
		});
		// 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
		// oks.setNotification(R.drawable.ic_launcher,
		// getString(R.string.app_name));
		// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
		// oks.setTitle(getString(R.string.share));
		// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
		// oks.setTitleUrl("http://139.129.57.83:8080/Appandroid/APPicon192.png");

		// text是分享文本，所有平台都需要这个字段
		// oks.setText("看视频学英语,名师上课超有用哦!");

		// 启动分享GUI
		oks.show(GrammarThirdActivity.this);

	}

	// public void deleteShare()
	// {
	//
	// File f = new File(getSDPath()+"/goldupload/");
	//
	// File[] fl = f.listFiles();
	// for (int i=0; i<fl.length; i++)
	// {
	// if(fl[i].toString().endsWith("out.jpg") ||
	// fl[i].toString().endsWith("out.jpg"))
	// {
	// if(fl[i].delete())
	// {
	// }else{
	// }
	// }
	// }
	// }

	public void clickShare2() {
		// ShareSDK.initSDK(scoreReportActivity.this);
		MobSDK.init(GrammarThirdActivity.this, "12c24ea0b59b0",
				"aae63565fbd69b1acbfcdd0d5ac0b35c");
		OnekeyShare oks = new OnekeyShare();
		// 关闭sso授权
		oks.disableSSOWhenAuthorize();
		oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {

			@Override
			public void onShare(Platform platform, ShareParams paramsToShare) {
				if (SinaWeibo.NAME.equals(platform.getName())) {
					paramsToShare.setTitle(getString(R.string.share));
					// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
					String url = "http://m.moregolden.com:36356/scorePage.html?moduleType=0&userType=0&time="
							+ Time
							+ "&mark="
							+ Score
							+ "&num="
							+ SPUtils.getString(GrammarThirdActivity.this,
									ConfigConstant.USERNAME) + "&exam_type=3";
					String title = SPUtils.getString(GrammarThirdActivity.this,
							"name")
							+ "在语法检测环节花费了"
							+ Time
							+ "秒获得"
							+ Score
							+ "分,为你点赞！";

					paramsToShare.setTitleUrl("http://m.moregolden.com:36356/scorePage.html?moduleType=0&userType=0&time="
							+ Time
							+ "&mark="
							+ Score
							+ "&num="
							+ SPUtils.getString(GrammarThirdActivity.this,
									ConfigConstant.USERNAME) + "&exam_type=3");
					paramsToShare.setTitle(SPUtils.getString(
							GrammarThirdActivity.this, "name")
							+ "在语法检测环节花费了"
							+ Time + "秒获得" + Score + "分,为你点赞！");
					// text是分享文本，所有平台都需要这个字段
					paramsToShare.setText(title + "\n\r想展现你的实力吗?来这里比拼一下吧！"
							+ url);
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
					paramsToShare
							.setImageUrl("http://139.129.57.83:8080/Appandroid/applogo.png");
					// url仅在微信（包括好友和朋友圈）中使用
					paramsToShare.setUrl("http://m.moregolden.com:36356/scorePage.html?moduleType=0&userType=0&time="
							+ Time
							+ "&mark="
							+ Score
							+ "&num="
							+ SPUtils.getString(GrammarThirdActivity.this,
									ConfigConstant.USERNAME) + "&exam_type=3");
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					paramsToShare.setComment("");
					// site是分享此内容的网站名称，仅在QQ空间使用
					paramsToShare.setSite(getString(R.string.app_name));
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					paramsToShare.setSiteUrl("http://m.moregolden.com:36356/scorePage.html?moduleType=0&userType=0&time="
							+ Time
							+ "&mark="
							+ Score
							+ "&num="
							+ SPUtils.getString(GrammarThirdActivity.this,
									ConfigConstant.USERNAME) + "&exam_type=3");

				} else {
					paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
					paramsToShare.setTitle(getString(R.string.share));
					// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
					paramsToShare.setTitleUrl("http://m.moregolden.com:36356/scorePage.html?moduleType=0&userType=0&time="
							+ Time
							+ "&mark="
							+ Score
							+ "&num="
							+ SPUtils.getString(GrammarThirdActivity.this,
									ConfigConstant.USERNAME) + "&exam_type=3");
					paramsToShare.setTitle(SPUtils.getString(
							GrammarThirdActivity.this, "name")
							+ "在语法检测环节花费了"
							+ Time + "秒获得" + Score + "分,为你点赞！");
					// text是分享文本，所有平台都需要这个字段
					paramsToShare.setText("想展现你的实力吗?来这里比拼一下吧！");
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
					paramsToShare
							.setImageUrl("http://139.129.57.83:8080/Appandroid/applogo.png");
					// url仅在微信（包括好友和朋友圈）中使用
					paramsToShare.setUrl("http://m.moregolden.com:36356/scorePage.html?moduleType=0&userType=0&time="
							+ Time
							+ "&mark="
							+ Score
							+ "&num="
							+ SPUtils.getString(GrammarThirdActivity.this,
									ConfigConstant.USERNAME) + "&exam_type=3");
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					paramsToShare.setComment("");
					// site是分享此内容的网站名称，仅在QQ空间使用
					paramsToShare.setSite(getString(R.string.app_name));
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					paramsToShare.setSiteUrl("http://m.moregolden.com:36356/scorePage.html?moduleType=0&userType=0&time="
							+ Time
							+ "&mark="
							+ Score
							+ "&num="
							+ SPUtils.getString(GrammarThirdActivity.this,
									ConfigConstant.USERNAME) + "&exam_type=3");

				}
			}
		});
		// 分享时Notification的图标和文字 2.5.9以后的版本不 调用此方法
		// oks.setNotification(R.drawable.ic_launcher,
		// getString(R.string.app_name));
		// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用

		// 启动分享GUI
		oks.show(this);
	}
}
